﻿using Aker.DevTeam;
using Aker.Uretim;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;

namespace Aker.Product
{
    public partial class YeniImalatKarti1 : XForm
    {
        public delegate void ProductInsertedEventHandler(int ProductId, string Artikel, int StokKartiTipi);
        public event ProductInsertedEventHandler ProductInserted;

        DataTable dtHammadde = null;
        DataTable dtRecete = null;
        DataTable dtMaliyet = null;

        DataTable dtIp = null;
        DataTable dtProductGLE = null;
        int GelenProductId = -1;
        bool siparisten = false;
        bool artikelden = false;

        bool loading = false;

        private void InitLocal()
        {
            if (Data.DB.Currency.Rows.Count == 0)
                Data.TAM.CurrencyTableAdapter.Fill(Data.DB.Currency);

            dtHammadde = Data.DM.ExecuteDataSet("GetHammaddeStok", 3, null).Tables[0];
            dtIp = dtHammadde.Select("GrupKodu like 'İ%'").CopyToDataTable();
            gleZeminIpi.Properties.Assign(Utility.GetAutoCompGLE(dtIp, "Grup", "GrupKodu"));
            gleZeminIpi.EditValue = dtIp.Rows[0]["GrupKodu"];

            dtProductGLE = Data.DM.ExecuteDataTable("GetProductGLE", 1);
            gleBazArtikel.Properties.Assign(Utility.GetAutoCompGLE(dtProductGLE, "Article", "Article"));
            gleBazArtikel.EditValueChanged += gleBazArtikel_EditValueChanged;

            gvMaliyet.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;

            dtRecete = new DataTable();
            dtRecete.Columns.Add("Oran", typeof(int));
            dtRecete.Columns.Add("GrupKodu", typeof(string));
            dtRecete.Columns.Add("HarmanKG", typeof(decimal));
            dtRecete.Columns.Add("FiiliStok", typeof(double));

            dtMaliyet = new DataTable();
            dtMaliyet.Columns.Add("ProductId", typeof(int));
            dtMaliyet.Columns.Add("Aciklama", typeof(string));
            dtMaliyet.Columns.Add("Fiyat", typeof(double));
            dtMaliyet.Columns.Add("CurrencyId", typeof(int));

            KafaYerlestir(false);

            txtPartiNo.Text = "1";

            seFire.EditValue = null;
            seGirisGramaj.EditValue = null;
            seFinalGramaj.EditValue = null;
            seKafa1.EditValue = null;
            seKafa2.EditValue = null;
            seKafa3.EditValue = null;
            seKafa4.EditValue = null;
            seOrguTuru.EditValue = null;
            seTumblerSuresi.EditValue = null;
            seFinalEn.EditValue = null;
            seRamIsi.EditValue = null;

            cmbGrup.SelectedIndex = 0;
            cmbUretimTipi.SelectedIndex = 1;
            cmbGrup.SelectedIndexChanged += cmbGrup_SelectedIndexChanged;

            InitReceteGvEvents(gv1, gv2, gv3, gv4, gv5, gv6, gv7, gv8);

            cmbUretimTipi.SelectedIndexChanged += cmbUretimTipi_SelectedIndexChanged;

            if (!AppSession.UserInfo.Yonetici)
                txtPartiNo.Enabled = txtYeniKod.Enabled = false;
        }


        public YeniImalatKarti1() //Ribbon'dan
        {
            InitializeComponent();

            InitLocal();

            InitReceteGv(dtRecete, gv1, gv2, gv3, gv4, gv5, gv6, gv7, gv8);
            InitMaliyetGv(dtMaliyet);

            GetNewCode();
        }

        public YeniImalatKarti1(int ProductId) //İmalat Kartından
        {
            InitializeComponent();

            InitLocal();

            GelenProductId = ProductId;
            LoadProductDetail(GelenProductId);
        }

        public YeniImalatKarti1(int ProductId,bool oldProduct) //Artikel listesinden
        {
            artikelden = true;
            InitializeComponent();

            InitLocal();

            GelenProductId = ProductId;
            LoadProductDetail(GelenProductId);
        }

        public YeniImalatKarti1(string bazArtikel, int uretimTipi, decimal qty, bool isKG) //Sipariş sayfasından
        {
            siparisten = true;
            InitializeComponent();

            InitLocal();

            teQty.EditValue = qty;
            //teQty.Enabled = false;

            if (bazArtikel != "")
            {
                //if (gleBazArtikel.GetSelectedDataRow() != null)
                {
                    gleBazArtikel.EditValue = bazArtikel;
                    int productId = (gleBazArtikel.GetSelectedDataRow() as DataRowView).Row["ProductId"].ToIntNN();
                    LoadProductDetail(productId);
                }
            }

            cmbMtKg.SelectedIndex = isKG ? 1 : 0;
            cmbUretimTipi.SelectedIndex = uretimTipi;

            GetNewCode();
        }

        private void GetNewCode()
        {
            string sonArtikel = "";
            Kod sonKod = null;
            string filtre = "";
            Kod Yeni = null;
            DataRow[] drsFiltered;
            string bazArtikel = gleBazArtikel.EditValue.ToStringNN();

            string filtreOnEk = "";
            switch (cmbGrup.SelectedIndex)
            {
                case 0: //20                    
                    filtreOnEk = "20." + DateTime.Now.Year.ToString().Substring(2, 2);
                    break;
                case 1: //10                    
                    filtreOnEk = "10." + DateTime.Now.Year.ToString().Substring(2, 2);
                    break;
                case 2:  //5000 
                    filtreOnEk = "5";
                    break;
                case 3:  //7000 
                    filtreOnEk = "7";
                    break;
                case 4:  //8000 
                    filtreOnEk = "8";
                    break;
                case 6: //9500
                    filtreOnEk = "95";
                    break;
                case 5: //9000
                    filtreOnEk = "9";
                    break;
            }

            switch (cmbUretimTipi.SelectedIndex)
            {
                case 0: //aynı artikel
                    if (bazArtikel == "")
                    {
                        ShowError("Baz artikel seçmelisiniz!");
                        return;
                    }

                    sonKod = new Kod(bazArtikel);
                    filtre = "Article like '" + sonKod.KodPartisiz + "%'";
                    drsFiltered = dtProductGLE.Select(filtre);
                    for (int i = drsFiltered.Length - 1; i > -1; i--)
                    {
                        DataRow dr = drsFiltered[i];
                        Kod arananKod = new Kod(dr["Article"].ToStringNN());
                        if (sonKod.Renk == arananKod.Renk)
                        {
                            sonKod = arananKod.Copy();
                            break;
                        }
                    }

                    Yeni = sonKod.PartiNoArtir();
                    txtYeniKod.Text = Yeni.KodPartisiz;
                    txtPartiNo.Text = Yeni.PartiNo;
                    break;
                case 1:  //yeni artikel
                    filtre = "Article like '" + filtreOnEk + "%'";
                    drsFiltered = dtProductGLE.Select(filtre);
                    if (drsFiltered.Length > 0)
                        sonArtikel = drsFiltered[drsFiltered.Length - 1]["Article"].ToStringNN();
                    else
                        sonArtikel = filtreOnEk + "000";

                    sonKod = new Kod(sonArtikel);

                    if (drsFiltered.Length > 0)
                        Yeni = sonKod.SiraNoArtir();
                    else
                        Yeni = sonKod.Copy();

                    txtYeniKod.Text = Yeni.KodPartisiz;
                    txtPartiNo.Text = Yeni.PartiNo;
                    break;
                case 2: //renk
                    if (bazArtikel == "")
                    {
                        ShowError("Baz artikel seçmelisiniz!");
                        return;
                    }

                    sonKod = new Kod(bazArtikel);

                    filtre = "Article like '" + sonKod.KodRenksizPartisiz + "%'";
                    drsFiltered = dtProductGLE.Select(filtre);
                    sonArtikel = drsFiltered[drsFiltered.Length - 1]["Article"].ToStringNN();

                    sonKod = new Kod(sonArtikel);
                    Yeni = sonKod.RenkOlustur();
                    txtYeniKod.Text = Yeni.KodPartisiz;
                    txtPartiNo.Text = Yeni.PartiNo;
                    break;
            }

            AppSession.MainForm.Notify("Baz alınan kod:" + sonKod.KodPartili);

        }

        private void InitMaliyetGv(DataTable dtMaliyet)
        {
            gvMaliyet.Init(dtMaliyet);
            gvMaliyet.Columns["CurrencyId"].ColumnEdit = Utility.GetAutoCompGLE(Data.DB.Currency, "Name", "CurrencyId");
            gvMaliyet.MakeColumnInvisible("ProductId", "ProductMaliyetId");
            gvMaliyet.SetCaptions("Aciklama:Masraf", "CurrencyId:Parabirimi");
            gvMaliyet.OptionsView.ShowViewCaption = false;
        }

        private void InitReceteGvEvents(params GridView[] gvs)
        {
            foreach (GridView gv in gvs)
                gv.CellValueChanged += gvKafa_CellValueChanged;
        }

        private void InitReceteGv(DataTable dtData, params GridView[] gvs)
        {
            foreach (GridView gv in gvs)
            {
                DataTable dt = dtData.Copy();

                gv.Init(dt);
                gv.OptionsView.ShowViewCaption = false;
                gv.MakeReadOnly("GrupKodu", "Oran", "HarmanKG");
                gv.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
                DevExpress.XtraEditors.Repository.RepositoryItemGridLookUpEdit ri = Utility.GetAutoCompGLE(dtHammadde, "Grup", "GrupKodu");

                ri.View.EnableComplexFiltering("Grup");
                gv.Columns["GrupKodu"].ColumnEdit = ri;

                gv.FormatAsNumber("HarmanKg");
                gv.BestFitColumns();

            }
        }

        private void LoadProductDetail(int id, bool onlyBazArtikelChanged = false)
        {
            //todo: load kısmında yüklenmeli
            //InitMaliyetGv(dtMaliyet);
            //InitReceteGv(dtRecete, gv1, gv2, gv3, gv4);


            //cmbGrup.SelectedIndex = 0;
            //cmbKompozisyon20.SelectedIndex = 0;
            //cmbCins.SelectedIndex = 0;

            LoadSentezDetail();

            DataSet dsProductDetail = Data.DM.ExecuteDataSet("GetProductDetail", id);

            DataTable dtMaliyet = dsProductDetail.Tables[2];
            InitMaliyetGv(dtMaliyet);


            if (dsProductDetail.Tables[0].Rows.Count == 0) //Yeni kart veya artikel listesinden
            {
                InitReceteGv(dtRecete, gv1, gv2, gv3, gv4);
                if (GelenProductId == -1) //Yeni kart
                    return;
                else //Artikel listesinden
                {
                    AkerDB.ProductRow pr = Data.DB.Product.FindByProductId(GelenProductId);
                    AkerDB.ProductDetayRow pd = Data.DB.ProductDetay.NewProductDetayRow();
                    pd.ProductId = GelenProductId;
                    Data.DB.ProductDetay.AddProductDetayRow(pd);

                    txtYeniKod.Text = pr.Article;
                    txtDesenNo.Text = pr.Design;
                    
                    if (!pr.IsPartiNoNull())
                        txtPartiNo.Text = pr.PartiNo.ToStringNN();

                    return;
                }
            }

            DataRow drDetail = dsProductDetail.Tables[0].Rows[0];

            cmbGrup.SelectedIndex = drDetail["ProductGrupId"].ToComboIndex();
            cmbKompozisyon20.SelectedIndex = drDetail["KompozisyonId"].ToComboIndex();
            txtDesenNo.Text = drDetail["DesenNo"].ToStringNN();
            txtRenk.Text = drDetail["Renk"].ToStringNN();
            cmbCins.SelectedIndex = drDetail["ProductCinsId"].ToComboIndex();
            seFire.EditValue = drDetail["Fire"].ToIntNN(0);
            seGirisGramaj.EditValue = drDetail["GirisGr"].ToIntNN(0);
            seFinalGramaj.EditValue = drDetail["FinishGr"].ToIntNN(0);

            txtKafa1.Text = drDetail["KafaRenk1"].ToStringNN();
            txtKafa2.Text = drDetail["KafaRenk2"].ToStringNN();
            txtKafa3.Text = drDetail["KafaRenk3"].ToStringNN();
            txtKafa4.Text = drDetail["KafaRenk4"].ToStringNN();

            seKafa1.EditValue = drDetail["KafaOran1"].ToIntNN(0);
            seKafa2.EditValue = drDetail["KafaOran2"].ToIntNN(0);
            seKafa3.EditValue = drDetail["KafaOran3"].ToIntNN(0);
            seKafa4.EditValue = drDetail["KafaOran4"].ToIntNN(0);

            cmbCins1.SelectedIndex = drDetail["KafaCins1"].ToComboIndex();
            cmbCins2.SelectedIndex = drDetail["KafaCins2"].ToComboIndex();
            cmbCins3.SelectedIndex = drDetail["KafaCins3"].ToComboIndex();
            cmbCins4.SelectedIndex = drDetail["KafaCins4"].ToComboIndex();

            if (teQty.Visible == true && !onlyBazArtikelChanged)
                teQty.Text = drDetail["QtyManuel"].ToStringNN();

            DataRow[] drs = dsProductDetail.Tables[1].Select("KafaNo=" + 1);
            if (drs.Length > 0)
                InitReceteGv(drs.CopyToDataTable(), gv1);
            else
                InitReceteGv(dtRecete, gv1);

            drs = dsProductDetail.Tables[1].Select("KafaNo=" + 2);
            if (drs.Length > 0)
                InitReceteGv(drs.CopyToDataTable(), gv2);
            else
                InitReceteGv(dtRecete, gv2);

            drs = dsProductDetail.Tables[1].Select("KafaNo=" + 3);
            if (drs.Length > 0)
                InitReceteGv(drs.CopyToDataTable(), gv3);
            else
                InitReceteGv(dtRecete, gv3);

            drs = dsProductDetail.Tables[1].Select("KafaNo=" + 4);
            if (drs.Length > 0)
                InitReceteGv(drs.CopyToDataTable(), gv4);
            else
                InitReceteGv(dtRecete, gv4);

            gleZeminIpi.EditValue = drDetail["ZeminIpiGrupKodu"].ToString();

            txtSıklık.Text = drDetail["SIKLIK"].ToStringNN();
            seTumblerSuresi.EditValue = drDetail["TumblrSuresi"].ToIntNN(0);
            seRamIsi.EditValue = drDetail["RamIsi"].ToIntNN(0);
            seFinalEn.EditValue = drDetail["FinalEn"].ToIntNN(0);

            seOrguTuru.EditValue = drDetail["OrguTuru"].ToIntNN(0);
            txtHavalar.Text = drDetail["Havalar"].ToStringNN();
            txtTumblerIsisi.Text = drDetail["TumblrIsisi"].ToStringNN();
            txtHavBoyu.Text = drDetail["HavBoyu"].ToStringNN();
            txtRaporBoyu.Text = drDetail["RaporBoyu"].ToStringNN();

            cmbMakasGrubu.Text = drDetail["MakasGrubu"].ToStringNN();
            txtAciklama.Text = drDetail["Aciklama"].ToStringNN();

            cmbTarakGrubu.SelectedIndex = drDetail["TarakGrubuId"].ToComboIndex();
            cmbZeminIpiTipi.SelectedIndex = drDetail["ZeminIpiTipiId"].ToComboIndex();
            cmbIgneCesidi.SelectedIndex = drDetail["IgneCesidiId"].ToComboIndex();
            cmbRamId.SelectedIndex = drDetail["RamId"].ToComboIndex();
            cmbDekatur.SelectedIndex = drDetail["DekaturId"].ToComboIndex();

            chkDink.Checked = (bool)drDetail["Dink"];
            chkSanfor.Checked = (bool)drDetail["Sanfor"];

            if (drDetail["Sardon"] != DBNull.Value)
                cmbSardon.SelectedIndex = drDetail["Sardon"].ToIntNN();

        }

        private void Save20(AkerDB.ProductDetayRow drDetay)
        {
            drDetay.ProductGrupId = cmbGrup.SelectedIndex + 1;
            drDetay.Renk = txtRenk.Text;
            drDetay.DesenNo = txtDesenNo.Text;
            drDetay.KompozisyonId = cmbKompozisyon20.SelectedIndex + 1;
            drDetay.ProductCinsId = cmbCins.SelectedIndex + 1;

            drDetay.ReferansArtikel = gleBazArtikel.EditValue.ToStringNN();
            drDetay.KafaRenk1 = txtKafa1.Text;
            drDetay.KafaOran1 = seKafa1.EditValue.ToIntNN();
            drDetay.KafaCins1 = cmbCins1.SelectedIndex + 1;

            drDetay.FinishGr = seFinalGramaj.EditValue.ToIntNN();
            if (drDetay.FinishGr < 1)
                drDetay.SetFinishGrNull();

            drDetay.GirisGr = seGirisGramaj.EditValue.ToIntNN(); ;
            if (drDetay.GirisGr < 1)
                drDetay.SetGirisGrNull();

            drDetay.Fire = seFire.EditValue.ToIntNN();

            foreach (DataRow dr in (gv1.DataSource as DataView).Table.Rows)
            {
                AkerDB.ProductHammaddeRow drHammadde = Data.DB.ProductHammadde.NewProductHammaddeRow();
                drHammadde.ProductId = drDetay.ProductId;
                drHammadde.KafaNo = 1;

                drHammadde.GrupKodu = dr["GrupKodu"].ToString();
                drHammadde.Oran = dr["Oran"].ToIntNN();
                drHammadde.HarmanKg = dr["HarmanKg"].ToDecimalNN();

                Data.DB.ProductHammadde.Rows.Add(drHammadde);
                Data.TAM.ProductHammaddeTableAdapter.Update(drHammadde);
            }


            if (seKafa2.EditValue.ToIntNN() > 0)
            {
                drDetay.KafaOran2 = seKafa2.EditValue.ToIntNN();
                drDetay.KafaRenk2 = txtKafa2.Text;
                drDetay.KafaCins2 = cmbCins2.SelectedIndex + 1;

                foreach (DataRow dr in (gv2.DataSource as DataView).Table.Rows)
                {
                    AkerDB.ProductHammaddeRow drHammadde = Data.DB.ProductHammadde.NewProductHammaddeRow();
                    drHammadde.ProductId = drDetay.ProductId;
                    drHammadde.KafaNo = 2;
                    drHammadde.GrupKodu = dr["GrupKodu"].ToString();
                    drHammadde.Oran = dr["Oran"].ToIntNN();
                    drHammadde.HarmanKg = dr["HarmanKg"].ToIntNN();
                    Data.DB.ProductHammadde.Rows.Add(drHammadde);
                    Data.TAM.ProductHammaddeTableAdapter.Update(drHammadde);
                }
            }

            if (seKafa3.EditValue.ToIntNN() > 0)
            {
                drDetay.KafaOran3 = seKafa3.EditValue.ToIntNN();
                drDetay.KafaRenk3 = txtKafa3.Text;
                drDetay.KafaCins3 = cmbCins3.SelectedIndex + 1;

                foreach (DataRow dr in (gv3.DataSource as DataView).Table.Rows)
                {
                    AkerDB.ProductHammaddeRow drHammadde = Data.DB.ProductHammadde.NewProductHammaddeRow();
                    drHammadde.ProductId = drDetay.ProductId;
                    drHammadde.KafaNo = 3;
                    drHammadde.GrupKodu = dr["GrupKodu"].ToString();
                    drHammadde.Oran = dr["Oran"].ToIntNN();
                    drHammadde.HarmanKg = dr["HarmanKg"].ToIntNN();
                    Data.DB.ProductHammadde.Rows.Add(drHammadde);
                    Data.TAM.ProductHammaddeTableAdapter.Update(drHammadde);
                }
            }

            if (seKafa4.EditValue.ToIntNN() > 0)
            {
                drDetay.KafaOran4 = seKafa4.EditValue.ToIntNN();
                drDetay.KafaRenk4 = txtKafa4.Text;
                drDetay.KafaCins4 = cmbCins4.SelectedIndex + 1;

                foreach (DataRow dr in (gv4.DataSource as DataView).Table.Rows)
                {
                    AkerDB.ProductHammaddeRow drHammadde = Data.DB.ProductHammadde.NewProductHammaddeRow();
                    drHammadde.ProductId = drDetay.ProductId;
                    drHammadde.KafaNo = 4;
                    drHammadde.GrupKodu = dr["GrupKodu"].ToString();
                    drHammadde.Oran = dr["Oran"].ToIntNN();
                    drHammadde.HarmanKg = dr["HarmanKg"].ToIntNN();
                    Data.DB.ProductHammadde.Rows.Add(drHammadde);
                    Data.TAM.ProductHammaddeTableAdapter.Update(drHammadde);
                }
            }


            drDetay.TarakGrubuId = cmbTarakGrubu.SelectedIndex + 1;

            drDetay.ZeminIpiTipiId = cmbZeminIpiTipi.SelectedIndex + 1;

            drDetay.ZeminIpiGrupKodu = gleZeminIpi.EditValue.ToString();

            drDetay.SIKLIK = txtSıklık.Text;
            if (drDetay.SIKLIK == "")
                drDetay.SetSIKLIKNull();

            drDetay.OrguTuru = seOrguTuru.EditValue.ToIntNN();
            if (drDetay.OrguTuru < 1)
                drDetay.SetOrguTuruNull();

            drDetay.IgneCesidiId = cmbIgneCesidi.SelectedIndex + 1;

            drDetay.Aciklama = txtAciklama.Text;
            if (drDetay.Aciklama == "")
                drDetay.SetAciklamaNull();

            drDetay.Havalar = txtHavalar.Text;
            if (drDetay.Havalar == "")
                drDetay.SetHavalarNull();

            drDetay.MakasGrubu = cmbMakasGrubu.EditValue.ToStringNN();
            if (drDetay.MakasGrubu == "")
                drDetay.SetMakasGrubuNull();

            drDetay.TumblrSuresi = seTumblerSuresi.EditValue.ToIntNN();
            if (drDetay.TumblrSuresi < 0)
                drDetay.SetTumblrSuresiNull();

            drDetay.TumblrIsisi = txtTumblerIsisi.Text;
            if (drDetay.TumblrIsisi == "")
                drDetay.SetTumblrIsisiNull();

            drDetay.HavBoyu = txtHavBoyu.Text;
            if (drDetay.HavBoyu == "")
                drDetay.SetHavBoyuNull();

            drDetay.RaporBoyu = txtRaporBoyu.Text;
            if (drDetay.RaporBoyu == "")
                drDetay.SetRaporBoyuNull();

            drDetay.DekaturId = cmbDekatur.SelectedIndex + 1;
            drDetay.Dink = chkDink.Checked;
            drDetay.Sanfor = chkSanfor.Checked;

            drDetay.Sardon = cmbSardon.SelectedIndex + 1;
            drDetay.RamId = cmbRamId.SelectedIndex + 1;


            drDetay.RamIsi = seRamIsi.EditValue.ToIntNN();
            if (drDetay.RamIsi < 0)
                drDetay.SetRamIsiNull();

            drDetay.FinalEn = seFinalEn.EditValue.ToIntNN();
            if (drDetay.FinalEn < 1)
                drDetay.SetFinalEnNull();
            if (teQty.Visible == true)
                drDetay.QtyManuel = teQty.EditValue.ToDecimalNN();
        }

        public void HarmanHesapla()
        {
            double girisGramaj = Convert.ToDouble(seGirisGramaj.EditValue);
            if (girisGramaj < 1)
                return;

            int qty = teQty.EditValue.ToIntNN();
            if (qty < 1)
                return;

            //int ipAdedi = cmbZeminIpiTipi.SelectedIndex + 1;
            //string zeminIpi = gleZeminIpi.Text.Trim();

            //int zeminIpiGramaji = zeminIpi.Split('/')[0].ToIntNN() / 3;

            double fire = 1 + seFire.EditValue.ToIntNN() / 100.0;

            //double zeminIpiOrani = (zeminIpiGramaji / girisGramaj) * ipAdedi;
            //double carpan = (teQty.EditValue.ToIntNN() * girisGramaj / 1000.0) * 1.5;
            double carpan = (teQty.EditValue.ToIntNN() * girisGramaj / 1000.0) * (seFinalEn.Value.ToIntNN() / 100.0);

            //double zeminIpiQty = carpan * zeminIpiOrani;

            int zeminIpiOrani = 0;

            double hammaddeMT = carpan * (1 - zeminIpiOrani) * fire;
            double hammaddeKG = (1 - zeminIpiOrani) * fire; //TODO !!!

            double qtyHammadde = 0;
            if (cmbMtKg.SelectedIndex == 0)
                qtyHammadde = hammaddeMT;
            else
                qtyHammadde = hammaddeKG;

            HarmanHesapla(seKafa1, gv1, qtyHammadde);
            HarmanHesapla(seKafa2, gv2, qtyHammadde);
            HarmanHesapla(seKafa3, gv3, qtyHammadde);
            HarmanHesapla(seKafa4, gv4, qtyHammadde);
        }

        private void HarmanHesapla(SpinEdit seKafa, GridView gvKafa, double hammaddeQty)
        {
            if (gvKafa.DataSource == null)
                return;

            gvKafa.EndEditing();
            double kafaOran = seKafa.EditValue.ToIntNN() / 100.0;
            DataTable dtKafa = (gvKafa.DataSource as DataView).Table;
            foreach (DataRow dr in dtKafa.Rows)
            {
                double satirOran = dr["Oran"].ToIntNN() / 100.0;
                double qty = hammaddeQty * kafaOran * satirOran;
                double iQty = Math.Truncate(qty);
                if (qty - iQty >= 0.5)
                    qty = iQty + 1;
                else
                    qty = iQty + 0.5;

                dr["HarmanKg"] = qty;
            }
        }

        private void seHarman_EditValueChanged(object sender, EventArgs e)
        {
            HarmanHesapla();
            RenkBelirle();
        }

        private void gvKafa_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            if (!loading)
            {
                GridView gv = sender as GridView;
                if (e.Column.FieldName == "Grup")
                    gv.SetRowCellValue(e.RowHandle, "FiiliStok", dtHammadde.Select("GrupKodu='" + e.Value + "'")[0]["FiiliStok"].ToIntNN(0));

                if (e.Column.FieldName != "HarmanKG")
                    HarmanHesapla();
                gv.BestFitColumns();
            }
        }


        private void LoadSentezDetail()
        {
            DataSet ds = null;
            string bazArtikel = gleBazArtikel.EditValue.ToStringNN();
            try
            {
                ds = Data.DMServer.ExecuteDataSet("GetSentezArtikel", bazArtikel);
            }
            catch (Exception ex) //bağlantı yoksa!
            {
                //XtraMessageBox.Show(ex.ToString());
                ds = Data.DMLocal.ExecuteDataSet("GetSentezArtikelLocal", bazArtikel);
            }

            bool found = ds.Tables[0].Rows.Count > 0;
            gcSentez.Visible = found;

            if (!found)
                return;

            gcSentez.Text = bazArtikel + " Sentez Detayı";

            DataRow drSK = ds.Tables[0].Rows[0];
            DataTable dt = new DataTable();
            dt.Columns.Add(Language.Sentez.Attribute, typeof(string));
            dt.Columns.Add(Language.Sentez.Value, typeof(string));

            foreach (DataColumn dc in ds.Tables[0].Columns)
                dt.Rows.Add(dc.ColumnName, drSK[dc].ToStringNN());

            gvSK.Init(dt);
            gvSK.ViewCaption = Language.Sentez.StokKarti;
            gvSK.BestFitColumns();

            gvHammadde.Init(ds.Tables[1]);
            gvHammadde.ViewCaption = Language.Sentez.Hammadde;
            gvHammadde.MakeColumnInvisible("Article");
            gvHammadde.SetCaptions("HammaddeSira:#", "Iplik:" + Language.Sentez.Hammadde, "IplikAciklama:" + Language.Sentez.Aciklama, "IplikMiktar:" + Language.Sentez.Kullanim, "Detay:" + Language.Sentez.Detail);
            gvHammadde.BestFitColumns();

            gvAciklama.Init(ds.Tables[2]);
            gvAciklama.ViewCaption = Language.Sentez.StokKartiDetayi;
            gvAciklama.MakeColumnInvisible("Article");
            gvAciklama.SetCaptions("AciklamaSira:#", "Aciklama:" + Language.Sentez.Aciklama);
            gvAciklama.BestFitColumns();
        }

        private void cmbUretimTipi_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!loading)
                GetNewCode();
        }

        private void cmbCins_SelectedIndexChanged(object sender, EventArgs e)
        {
            int duz = 0;
            int bukle = 0;

            if (txtKafa1.Text != "")
                if (cmbCins1.SelectedIndex == 0)
                    duz++;
                else
                    bukle++;

            if (txtKafa2.Text != "")
                if (cmbCins2.SelectedIndex == 0)
                    duz++;
                else
                    bukle++;

            if (txtKafa3.Text != "")
                if (cmbCins3.SelectedIndex == 0)
                    duz++;
                else
                    bukle++;

            if (txtKafa4.Text != "")
                if (cmbCins4.SelectedIndex == 0)
                    duz++;
                else
                    bukle++;

            //Düz Bukle
            //Bukle Bukle
            //Normal Düz
            //1 Düz-2 Bukle
            //2 Bukle-1 Düz
            //2 Düz-2 Bukle
            //3 Düz-1 Bukle

            if (duz == 1 && bukle == 1)
                cmbCins.SelectedIndex = 0;
            else if (duz == 0 && bukle == 2)
                cmbCins.SelectedIndex = 1;

            else if (duz == 2 && bukle == 0)
                cmbCins.SelectedIndex = 2;

            else if (duz == 1 && bukle == 2)
                cmbCins.SelectedIndex = 3;

            else if (duz == 1 && bukle == 2)
                cmbCins.SelectedIndex = 4;

            else if (duz == 2 && bukle == 2)
                cmbCins.SelectedIndex = 5;

            else if (duz == 3 && bukle == 1)
                cmbCins.SelectedIndex = 6;

            else if (duz == 2 && bukle == 1)
                cmbCins.SelectedIndex = 7;
            else if (bukle == 4)
                cmbCins.SelectedIndex = 8;
        }

        private void btnKaydet_Click(object sender, EventArgs e)
        {
            if (seGirisGramaj.EditValue.ToIntNN() == -1)
            {
                ShowError("Giriş gramajı boş bırakamazsınız !");
                return;
            }

            gv1.EndEditing();
            gv2.EndEditing();
            gv3.EndEditing();
            gv4.EndEditing();

            AkerDB.ProductRow drProduct = null;
            AkerDB.ProductDetayRow drDetay = null;

            if (siparisten)
            {
                drProduct = Data.DB.Product.NewProductRow();
                Data.DB.Product.AddProductRow(drProduct);

                drDetay = Data.DB.ProductDetay.NewProductDetayRow();
                Data.DB.ProductDetay.Rows.Add(drDetay);
            }
            else if (artikelden)
            {
                drProduct = Data.DB.Product.FindByProductId(GelenProductId);
                drDetay = (AkerDB.ProductDetayRow)Data.DB.ProductDetay.Select("ProductId = " + drProduct.ProductId)[0];
            }
            else
            {
                Data.TAM.ProductDetayTableAdapter.Fill(Data.DB.ProductDetay);
                drProduct = Data.DB.Product.FindByProductId(GelenProductId);
                drDetay = (AkerDB.ProductDetayRow)Data.DB.ProductDetay.Select("ProductId = " + drProduct.ProductId)[0];
            }


            drProduct.Article = txtYeniKod.Text;
            drProduct.PartiNo = txtPartiNo.Text.ToIntNN();
            drProduct.ModifiedBy = AppSession.UserInfo.UserId;
            drProduct.ModifiedOn = DateTime.Now;

            Data.SaveProduct(drProduct);

            drDetay.ProductId = drProduct.ProductId;


            Save20(drDetay);
            foreach (DataRow dr in (gvMaliyet.DataSource as DataView).Table.Rows)
            {
                AkerDB.ProductMaliyetRow drMaliyet = Data.DB.ProductMaliyet.NewProductMaliyetRow();
                drMaliyet.ProductId = drProduct.ProductId;
                drMaliyet.Aciklama = dr["Aciklama"].ToStringNN();
                drMaliyet.CurrencyId = dr["CurrencyId"].ToIntNN();
                drMaliyet.Fiyat = dr["Fiyat"].ToDecimalNN();
                Data.DB.ProductMaliyet.Rows.Add(drMaliyet);
                Data.TAM.ProductMaliyetTableAdapter.Update(drMaliyet);
            }

            Data.TAM.ProductDetayTableAdapter.Update(drDetay);

            if (Environment.MachineName != "KGULCAN")
                btnKaydet.Enabled = false;

            GelenProductId = drProduct.ProductId;


            if (!siparisten) //siparişten geliyorsa, productId sipariş formunda güncelleniyor ve rapor sonra gösteriliyor...
                AppSession.MainForm.ShowMdiChildForm(typeof(ImalatKartlari), GelenProductId);

            if (ProductInserted != null)
                ProductInserted(GelenProductId, drProduct.Article, 1);

        }

        private void gleBazArtikel_EditValueChanged(object sender, EventArgs e)
        {
            cmbGrup.SelectedIndexChanged -= cmbGrup_SelectedIndexChanged;
            cmbUretimTipi.SelectedIndexChanged -= cmbUretimTipi_SelectedIndexChanged;

            if (gleBazArtikel.Text.StartsWith("20."))
                cmbGrup.SelectedIndex = 0;
            if (gleBazArtikel.Text.StartsWith("10."))
                cmbGrup.SelectedIndex = 1;
            if (gleBazArtikel.Text.StartsWith("5"))
                cmbGrup.SelectedIndex = 2;
            if (gleBazArtikel.Text.StartsWith("7"))
                cmbGrup.SelectedIndex = 3;
            if (gleBazArtikel.Text.StartsWith("8"))
                cmbGrup.SelectedIndex = 4;
            if (gleBazArtikel.Text.StartsWith("9"))
                if (gleBazArtikel.Text.Substring(1, 1).ToIntNN() < 5)
                    cmbGrup.SelectedIndex = 5;
                else
                    cmbGrup.SelectedIndex = 6;

            int bazProductId = (gleBazArtikel.GetSelectedDataRow() as DataRowView).Row["ProductId"].ToIntNN();
            LoadProductDetail(bazProductId, true);

            GetNewCode();

            cmbUretimTipi.SelectedIndexChanged += cmbUretimTipi_SelectedIndexChanged;
            cmbGrup.SelectedIndexChanged += cmbGrup_SelectedIndexChanged;

            //TODO:KG BazProductId = gleBazArtikel.EditValue.ToIntNN();
        }

        private void cmbMtKg_SelectedIndexChanged(object sender, EventArgs e)
        {
            HarmanHesapla();
        }

        private void btnCikis_Click(object sender, EventArgs e)
        {
            AppSession.MainForm.ShowMdiChildForm(typeof(ImalatCikis), GelenProductId);
        }

        #region KafaGrid Yerlesimi
        private void seKafaAdedi_EditValueChanged(object sender, EventArgs e)
        {
            int adet = seKafaAdedi.Value.ToIntNN();

            bool v = adet > 1;
            lblK2.Visible = v;
            seKafa2.Visible = v;
            txtKafa2.Visible = v;
            cmbCins2.Visible = v;
            gc2.Visible = v;

            v = adet > 2;
            lblK3.Visible = v;
            seKafa3.Visible = v;
            txtKafa3.Visible = v;
            cmbCins3.Visible = v;
            gc3.Visible = v;

            v = adet > 3;
            lblK4.Visible = v;
            seKafa4.Visible = v;
            txtKafa4.Visible = v;
            cmbCins4.Visible = v;
            gc4.Visible = v;

            v = adet > 4;
            lblK5.Visible = v;
            seKafa5.Visible = v;
            txtKafa5.Visible = v;
            cmbCins5.Visible = v;
            gc5.Visible = v;

            v = adet > 5;
            lblK6.Visible = v;
            seKafa6.Visible = v;
            txtKafa6.Visible = v;
            cmbCins6.Visible = v;
            gc6.Visible = v;

            v = adet > 6;
            lblK7.Visible = v;
            seKafa7.Visible = v;
            txtKafa7.Visible = v;
            cmbCins7.Visible = v;
            gc7.Visible = v;

            v = adet > 7;
            lblK8.Visible = v;
            seKafa8.Visible = v;
            txtKafa8.Visible = v;
            cmbCins8.Visible = v;
            gc8.Visible = v;

            if (adet > 4)
                KafaYerlestir(true);
            else
                KafaYerlestir(false);
        }


        private void KafaYerlestir(bool dortdenFazla)
        {
            if (dortdenFazla)
            {
                gcRecete.Width = 1684;
                gcSentez.Location = new System.Drawing.Point(867, 541);
            }
            else
            {
                gcRecete.Width = 849;
                gcSentez.Location = new System.Drawing.Point(867, 12);
            }
        }
        #endregion

        private void seFinalEn_EditValueChanged(object sender, EventArgs e)
        {
            HarmanHesapla();
        }

        private void txtRenk_TextChanged(object sender, EventArgs e)
        {
            RenkBelirle();
        }

        private void RenkBelirle()
        {
            List<string> colors = new List<string>();
            txtRenk.Text = "";

            if (txtDesenNo.Text.Length > 0)
            {
                string firstChar = txtDesenNo.Text.Substring(0, 1);
                if (firstChar.ToIntNN() > 1)
                    txtRenk.Text = firstChar + " Renkli";
            }

            if (seKafa1.Value > 0)
                colors.Add(txtKafa1.Text.CamelCasing());
            if (seKafa2.Value > 0)
                colors.Add(txtKafa2.Text.CamelCasing());
            if (seKafa3.Value > 0)
                colors.Add(txtKafa3.Text.CamelCasing());
            if (seKafa4.Value > 0)
                colors.Add(txtKafa4.Text.CamelCasing());

            if (colors.Count > 0)
                if (txtRenk.Text.Length > 0)
                    txtRenk.Text += " - " + string.Join(" ", colors);
                else
                    txtRenk.Text = string.Join(" ", colors);
        }

        void cmbGrup_SelectedIndexChanged(object sender, EventArgs e)
        {
            gleBazArtikel.EditValue = null;
            if (!loading)
                GetNewCode();
        }
    }
}